import { defineStore } from 'pinia';
import { Config } from 'src/types';
import { ref, Ref, watch } from 'vue';
import { getDocDirname, pathJoin } from 'src/api/SysApi';
import { getFile, saveFile } from 'src/api/FileApi';
import yaml from 'js-yaml';
import { useProjectStore } from 'stores/projectStore';

export const useConfigStore = defineStore('config', () => {
  const sysConfigPath = pathJoin(getDocDirname(), 'Qianl Gen', 'config.yml');
  const config: Ref<Config> = ref({
    mac: 'string',
    deviceId: window.ipcCom.getUniqueId(),
    configFilePath: pathJoin(getDocDirname(), 'Qianl Gen', 'gen'),
    templateFilePath: pathJoin(getDocDirname(), 'Qianl Gen', 'gen', 'template'),
    projectName: 'define',
    projects: ['define'],
  });
  const saveTimer:Ref<null| NodeJS.Timer> = ref(null);
  watch(
    config,
    () => {
      if (saveTimer.value) clearTimeout(saveTimer.value);
      saveTimer.value = setTimeout(async () => {
        await refresh(config.value);
      }, 10);
    },
    { deep: true }
  );
  const getConfig = async (): Promise<unknown> => {
    return new Promise(async (resolve) => {
      const sysConfigData = await getFile(sysConfigPath, true);
      if (!sysConfigData) {
        await refresh(config.value);
        resolve(config.value);
      } else {
        config.value = yaml.load(sysConfigData) as Config;
        resolve(config.value);
      }
    });
  };
  const refresh = async (data?: Config) => {
    return new Promise((resolve) => {
      console.log('refresh src', data);
      saveFile(sysConfigPath, yaml.dump(data)).then((r: string) => {
        useProjectStore().getProject();
        resolve(r);
      });
    });
  };
  return {
    getConfig,
    refresh,
    config,
  };
});
